
<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card" style="padding: 36px">
        <el-steps :active="active" finish-status="success" simple>
          <el-step title="课程信息" />
          <el-step title="其他信息" />
          <el-step title="章节信息" />
        </el-steps>
        <div style="padding: 36px">
          <el-form v-show="active === 0" ref="courseForm" :model="courseForm" :rules="rules" label-width="80px">
            <el-form-item label="课程名称" prop="name">
              <el-input v-model="courseForm.name" placeholder="请输入课程名称" style="width: 40%" />
            </el-form-item>
            <el-form-item label="适用地区" prop="province">
              <el-select
                v-model="courseForm.province"
                remote
                filterable
                placeholder="请选择地区"
                :remote-method="remoteMethod"
                :loading="selectload"
                style="width: 40%"
                @change="selectRegion"
              >
                <el-option v-for="(item, index) in cityList" :key="index" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="课程科目" prop="subject">
              <el-select v-model="courseForm.subject" filterable placeholder="请选择科目" style="width: 40%">
                <el-option v-for="(item, index) in subjectList" :key="index" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="课程封面" prop="cover">
              <el-upload
                :headers="headers"
                class="avatar-uploader"
                :action="host + '/api/v1/public/uploadFile'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="courseForm.cover" :src="courseForm.cover" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="课程状态" prop="status">
              <el-switch
                v-model="courseForm.status"
                :active-value="1"
                :inactive-value="-1"
                active-text="上架"
                inactive-text="下架"
              />
            </el-form-item>
            <el-form-item label="课程价格" prop="price">
              <el-input-number v-model="courseForm.price" controls-position="right" placeholder="请输入课程价格" />
            </el-form-item>
            <el-form-item label="课程描述" prop="introduction">
              <el-row :gutter="3" style="margin-left: 0;display: flex"">
                <Pictures
                  v-for="(item, index) in courseForm.introduction"
                  :key="index"
                  :url="item"
                  :index="index"
                  @deletefile="handleRemove"
                />
                <el-upload
                  :headers="headers"
                  class="avatar-uploader"
                  :action="host + '/api/v1/public/uploadFile'"
                  :show-file-list="false"
                  :on-success="handleAvatarOutline"
                  :before-upload="beforeAvatarUpload"
                >
                  <i class="el-icon-plus avatar-uploader-icon" />
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
                </el-upload>
              </el-row>
            </el-form-item>
          </el-form>

          <el-form
            v-show="active === 1"
            ref="lecturerForm"
            :model="lecturerForm"
            :rules="rules"
            label-position="right"
            label-width="106px"
          >
            <el-form-item label="教师介绍" prop="lecturer_id">
              <el-select v-model="lecturerForm.lecturer_id" filterable placeholder="请选择教师" style="width: 40%">
                <el-option v-for="item in teacherList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <!--            <el-form-item label="直播日期" prop="start_time">-->
            <!--              <el-date-picker-->
            <!--                v-model="lecturerForm.start_time"-->
            <!--                type="datetimerange"-->
            <!--                range-separator="至"-->
            <!--                start-placeholder="开始日期"-->
            <!--                end-placeholder="结束日期"-->
            <!--                value-format="yyyy-MM-dd HH:mm:ss"-->
            <!--                style="width: 40%"-->
            <!--              />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="直播地址" prop="live_url">-->
            <!--              <el-input v-model="lecturerForm.live_url" placeholder="请输入直播地址" style="width: 40%" />-->
            <!--            </el-form-item>-->
          </el-form>
          <el-form v-if="active === 2">
            <div style="display: flex; justify-content: flex-end;">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="addChapter">添加章节</el-button>
            </div>
            <div v-if="chapterData.length > 0">
              <Chapter
                v-for="(item, index) in chapterData"
                :key="index"
                :chapter-key="index"
                :chapter-item="item"
                :host="host"
                :headers="headers"
                :subject="courseForm.subject"
                @say="parentSay"
                @dialogVisible="addChapter"
                @getDetails="getDetails"
              />
            </div>
            <el-empty v-else :image-size="150" />
          </el-form>
          <div style="float:right">
            <el-button v-show="active !== 0" style="margin-top: 12px;" @click="lastStep">上一步</el-button>
            <el-button type="primary" style="margin-top: 12px;" @click="submitForm">{{ active === 2 ? '确认' : '下一步' }}
            </el-button>
          </div>
        </div>
      </el-card>
      <Video :show-video="showVideo" :play-url="playUrl" @handleHideModal="handleHideModal" />
      <!--      添加大章节-->
      <el-dialog title="添加章节" :visible.sync="visible" destroy-on-close @closed="onClosed">
        <el-form ref="form" :model="form" :rules="chapterRules" label-width="80px">
          <el-form-item label="章节名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <!--          <el-form-item label="直播日期" prop="zb_date">-->
          <!--            <el-date-picker-->
          <!--              v-model="form.zb_date"-->
          <!--              type="date"-->
          <!--              placeholder="直播日期">-->
          <!--            </el-date-picker>-->
          <!--          </el-form-item>-->
          <el-form-item label="是否免费" prop="is_free">
            <el-switch
              v-model="form.is_free"
              :active-value="1"
              :inactive-value="0"
              active-text="是"
              inactive-text="否"
            />
          </el-form-item>
          <el-form-item label="备注" prop="note">
            <el-input v-model="form.note" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitChapterForm">确 定</el-button>
        </div>
      </el-dialog>
    </template>
  </BasicLayout>
</template>

<script>
import {
  getCity,
  addCourse,
  editCourse,
  getSubject,
  getDetails,
  editChapter,
  addChapter,
  delChapter,
  getSave,
  editLiveCourse,
  addLiveCourse,
  getLiveCourse,
  editLiveChapter,
  addLiveChapter,
  delLiveChapter
} from '@/api/admin/sys-course'
import { getToken } from '@/utils/auth'
import { getLeacher } from '@/api/admin/sys-teacher'
import { clients, getNowDate } from '@/utils/index'
import Video from '@/components/Video'
import Pictures from '@/components/Pictures'
import Chapter from './chapter'
export default {
  components: {
    Video,
    Pictures,
    Chapter
  },
  data() {
    return {
      headers: { Authorization: 'Bearer ' + getToken() },
      host: '',
      active: 0,
      flagchange: 0,
      lecturerchange: 0,
      isChange: false,
      courseForm: {
        cover: null,
        status: -1,
        subject: null,
        introduction: []
      },
      lecturerForm: {
        course_type: 'live'
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '课程名称不能为空', trigger: 'blur' }
        ],
        subject: [
          { required: true, message: '课程科目不能为空', trigger: 'blur' }
        ],
        cover: [{ required: true, message: '上传课程封面', trigger: 'blur' }],
        status: [{ required: true, message: '选择课程状态', trigger: 'blur' }],
        price: [
          { required: true, message: '课程价格不能为空', trigger: 'blur' }
        ],
        introduction: [
          { required: true, message: '课程简介不能为空', trigger: 'blur' }
        ],
        lecturer_id: [{ required: true, message: '选择教师', trigger: 'blur' }],
        province: [
          { required: true, message: '选择适用地区', trigger: 'blur' }
        ],
        start_time: [
          { required: true, message: '日期不能为空', trigger: 'blur' }
        ],
        live_url: [
          { required: true, message: '直播地址不能为空', trigger: 'blur' }
        ]
      },
      cityList: [],
      teacherList: [],
      courseId: null,
      subjectList: [],
      selectload: false,
      loading: false,
      showVideo: false,
      playUrl: '',
      percentage: 0,
      chapterRules: {
        name: [{ required: true, message: '输入章节名称', trigger: 'blur' }]
      },
      visible: false,
      form: { is_free: 0 },
      chapterData: [],
      chapterKey: -1
    }
  },
  watch: {
    courseForm: {
      deep: true,
      handler(val) {
        this.flagchange++
        if (this.flagchange > 2) {
          // 说明监听值有变化
          this.isChange = true // 弹框提示
        }
        if (val.province) {
          getSubject({ province: val.province }).then(res => {
            this.subjectList = res?.data || []
          })
        }
      }
    },
    lecturerForm: {
      deep: true,
      handler(val) {
        this.lecturerchange++
        if (this.lecturerchange > 1) {
          // 说明监听值有变化
          this.isChange = true // 弹框提示
        }
      }
    }
  },
  created() {
    this.host = process.env.VUE_APP_BASE_API
    getLeacher().then(res => {
      this.teacherList = res?.data || []
    })
    getCity().then(res => {
      this.cityList = res?.data || []
    })
    if (this.$route.params.id) {
      /** 获取课程详情 */
      this.courseId = this.$route.params && Number(this.$route.params.id)
      getLiveCourse(this.courseId).then(response => {
        // const { data = {}} = response
        // const courseInfor = {
        //   ...data?.live_step1,
        //   introduction: data?.live_step1?.introduction?.includes('://')
        //     ? data?.live_step1?.introduction.split(',')
        //     : []
        // }
        const courseInfor = response.data
        courseInfor.introduction = courseInfor.introduction?courseInfor.introduction.split(","): []
        this.courseForm = {
          ...courseInfor,
          price: courseInfor.price / 100
        }
        this.lecturerForm = {
          lecturer_id: courseInfor.lecturer_id,
          // start_time: [courseInfor.start_time, courseInfor.end_time]
        }
        this.chapterData = response.data?.course_ware_json
      })
    }
  },
  methods: {
    selectRegion(val) {
      this.courseForm.subject = null
      getSubject({ province: val }).then(res => {
        this.subjectList = res?.data || []
      })
    },
    traverseRender(data) {
      return data?.map(item => {
        return {
          key: item.id,
          value: item.id,
          label: item.label,
          children:
            item.children.length > 0 ? this.traverseRender(item.children) : null
        }
      })
    },
    // 上一步
    lastStep() {
      if (this.active-- < 1) return (this.active = 0)
    },
    // 下一步
    submitForm() {
      if (this.active === 0) {
        this.$refs['courseForm'].validate(courseValid => {
          if (courseValid) {
            this.active++
          } else {
            return
          }
        })
      } else if (this.active === 1) {
        this.$refs['lecturerForm'].validate(lecturerValid => {
          if (lecturerValid) {
            const payload = {
              live_step_1: {
                ...this.courseForm,
                price: this.courseForm.price * 100,
                introduction: this.courseForm.introduction.toString()
              },
              live_step_2: {
                ...this.lecturerForm,
                // start_time: this.lecturerForm.start_time[0],
                // end_time: this.lecturerForm.start_time[1]
              }
            }
            // console.log(payload, this.$route.params.id, this.isChange); return
            if (this.$route.params.id && this.isChange) {
              editLiveCourse({
                ...payload,
                course_id: this.courseId
              }).then(res => {
                console.log(res)
                if (res.code === 200) {
                  this.msgSuccess(res.msg)
                  this.active++
                  // this.$router.push('/admin/sys-course/live')
                } else {
                  this.msgError(res.msg)
                }
              })
            } else if (this.$route.params.id) {
              this.active++
              // this.$router.push('/admin/sys-course/live')
            } else {
              addLiveCourse(payload).then(res => {
                if (res.code === 200) {
                  this.msgSuccess(res.msg)
                  this.active++
                  this.courseId = res.data
                  // this.$router.push('/admin/sys-course/live')
                } else {
                  this.msgError(res.msg)
                }
              })
            }
          }
        })
      } else if (this.active === 2) {
        if (this.courseId) {
          getSave({
            link_type: 1,
            obj_id: this.courseId
          }).then(res => { })
        }
        this.$router.push('/admin/sys-course/live')
      }
    },
    // 添加章节
    addChapter(value) {
      if (value.type === 'delete') {
        if (value?.chapterItem?.id) {
          this.$confirm('是否确认删除', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            delLiveChapter({ id: value?.chapterItem?.id }).then(res => {
              if (res.code === 200) {
                this.chapterData = this.chapterData?.filter(
                  (item, index) => index !== value?.chapterKey
                )
              }
            })
          })
          return
        }
        this.chapterData = this.chapterData?.filter(
          (item, index) => index !== value?.chapterKey
        )
      } else {
        this.visible = true
        if (value?.chapterItem) {
          this.form = value?.chapterItem
          this.chapterKey = value?.chapterKey
        }
      }
    },
    submitChapterForm() { // 大章节 提交创建
      this.$refs['form'].validate(valid => {
        // console.log({
        //       ...this.form,
        //       pid: 0,
        //   course_id: this.courseId
        // }); return
        if (valid && this.chapterKey === -1) { // 新增
          if (this.courseId) {
            addLiveChapter({
              ...this.form,
              pid: 0,
              course_id: this.courseId
            }).then(res => {
              if (res.code === 200) {
                this.chapterData.push({
                  ...this.form,
                  id: res.data,
                  course_id: this.courseId,
                  children: []
                })
                this.visible = false
                this.chapterKey = -1
              }
            })
            return
          }
        } else if (valid && this.chapterKey !== -1) { // 编辑
          if (this.form.id) {
            editLiveChapter(this.form).then(response => {
              this.chapterData = this.chapterData.map((item, index) =>
                index === this.chapterKey
                  ? JSON.parse(JSON.stringify(this.form))
                  : item
              )
              this.visible = false
              this.chapterKey = -1
            })
          }
        }
      })
    },
    parentSay(msg) {
      this.chapterData = this.chapterData.map(item =>
        item.name === msg.name ? msg : item
      )
    },
    getDetails() {
      getLiveCourse(this.courseId).then(response => {
        const { data = {}} = response
        const courseInfor = {
          ...data?.step1,
          outline:
            data?.step1?.outline.length > 0
              ? data?.step1?.outline.split(',')
              : [],
          introduction: data?.step1?.introduction?.includes('://')
            ? data?.step1?.introduction.split(',')
            : []
        }
        this.courseForm = {
          ...courseInfor,
          price: courseInfor.price / 100
        }
        this.lecturerForm = data?.step2
        this.course_gift = data?.step2?.course_gift || [
          {
            gift_type: 'question_bank',
            obj_ids: ''
          },
          {
            gift_type: 'examination',
            obj_ids: ''
          }
        ]
        this.questionBankNumber = data?.step2?.course_gift[0]?.obj_ids
          ? data?.step2?.course_gift[0]?.obj_ids.split(',').map(Number)
          : []
        this.examinationNumber = data?.step2?.course_gift[1]?.obj_ids
          ? data?.step2?.course_gift[1]?.obj_ids.split(',').map(Number)
          : []
        this.chapterData = data?.course_ware_json
        console.log(this.chapterData)
      })
    },
    onClosed() {
      this.form = {}
      this.resetForm('form')
    },
    cancel() {
      this.visible = false
    },
    handleRemove(file) {
      this.courseForm.introduction = this.courseForm.introduction.filter(
        (item, index) => file !== index
      )
    },
    handleAvatarOutline(res) {
      this.courseForm.introduction.push(res.data.full_path)
    },
    handleAvatarSuccess(res) {
      this.courseForm.cover = res.data.full_path
    },

    beforeAvatarUpload(file) {
      const isLt05M = file.size / 1024 / 1024 < 5
      const isJPG = file.type.indexOf('image/') === -1
      if (isJPG) {
        this.$message.error(
          '文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件'
        )
      }
      if (!isLt05M) {
        this.$message.error('上传头像图片大小不能超过 500k!')
      }
      return !isJPG && isLt05M
    },
    remoteMethod(query) {
      if (query !== '') {
        this.selectload = true
        getCity({ name: query }).then(res => {
          this.cityList = res?.data || []
          this.selectload = false
        })
      } else {
        this.cityList = []
      }
    },
    playVideo(url) {
      this.showVideo = true
      this.playUrl = url
    },
    handleHideModal() {
      this.playUrl = ''
      this.showVideo = false
    },
    beforeRemove(event, file) {
      event.stopPropagation()
      return this.$confirm(`确定移除 ${file}？`)
        .then(() => {
          this.courseForm.audition_link = ''
          this.courseForm.audition_course_name = ''
          this.percentage = 0
        })
        .catch(() => { })
    },
    async httpUpload(file) {
      try {
        // 判断扩展名
        const tmpcnt = file.file.name.lastIndexOf('.')
        const exname = file.file.name.substring(tmpcnt + 1)
        const client = clients()
        const names = ['wav', 'mp4']
        if (names.indexOf(exname) < 0) {
          this.$message.error('不支持的格式!')
          return
        }
        this.loading = true
        const imgUrl = 'http://tw.img.twzxjy.com'
        const fileName = `static/uploadfile/${getNowDate()}/${file.file.uid
        }.${exname}`
        // 依次填写Object完整路径（例如exampledir/exampleobject.txt）和本地文件的完整路径（例如D:\\localpath\\examplefile.txt）。Object完整路径中不能包含Bucket名称。
        // 如果本地文件的完整路径中未指定本地路径（例如examplefile.txt），则默认从示例程序所属项目对应本地路径中上传文件。
        await client.multipartUpload(fileName, file.file, {
          progress: (p, cpt, res) => {
            // 获取分片上传进度、断点和返回值。
            this.percentage = (Math.floor(p * 100) / 100) * 100
            if (p === 1) {
              this.loading = false
            }
          },
          parallel: 5, // 并发上传的分片数量
          partSize: 1024 * 1024 * 20,
          // headers,
          // 指定meta参数，自定义Object的元信息。通过head接口可以获取到Object的meta数据。
          meta: {
            year: 2020,
            people: 'test'
          },
          mime: file.type // 上传文件类型
        })
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        const head = await client.head(fileName)
        if (head.status === 200) {
          this.$set(this.courseForm, 'audition_link', `${imgUrl}/${fileName}`)
          this.$set(this.courseForm, 'audition_course_name', file.file.name)
        }
      } catch (e) {
        if (e.code === 'ConnectionTimeoutError') {
          console.log('TimeoutError')
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

::v-deep .el-form-item__content {
  .el-progress {
    line-height: 2.3;
  }
}
</style>
